/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.web.jsf.orchestra;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * handles double submit, reload and browser back requests.
 * If such an actions is detected, we get the users latest response (within the same ConversationContext) from the {@link LastResponseHolder} and repeat that response.
 *
 * @author Manfred Geiler
 */
class TransactionTokenHandler
{
    private static final Logger LOG = Logger.getLogger(TransactionTokenHandler.class.getName());

    public void handleDoubleSubmitOrReload(FacesContext facesContext)
    {
        if (isHttpGetRequest(facesContext))
        {
            //ignore double submit for GET requests - a redirect would lead to an endless loop in the browser!
            LOG.fine("Double Submit or reload detected but ignored because this is a GET request");
        }
        else
        {
            LOG.info("Double Submit or reload detected");
            restoreView(facesContext);
        }
    }

    public void handleBrowserBack(FacesContext facesContext)
    {
        LOG.info("Browser back detected");
        restoreView(facesContext);
    }

    public void handleUnknownRequest(FacesContext facesContext)
    {
        LOG.info("Unknown token discrepancy detected");
        restoreView(facesContext);
    }

    private void restoreView(FacesContext facesContext)
    {
        LastResponseHolder lastResponseHolder = LastResponseHolder.getCurrentInstance();
        if (lastResponseHolder == null)
        {
            throw new IllegalStateException("lastResponseHolder is null. maybe the url has no conversationContext id");
        }
        if (lastResponseHolder.isRedirect())
        {
            try
            {
                ((HttpServletResponse) facesContext.getExternalContext().getResponse()).sendRedirect(lastResponseHolder.getRedirectUrl());
            }
            catch (IOException ignore)
            {
            }
            finally
            {
                facesContext.responseComplete();
            }
        }
        else if (lastResponseHolder.getViewRoot() != null)
        {
            facesContext.setViewRoot(lastResponseHolder.getViewRoot());
            facesContext.renderResponse();
        }
        else
        {
            try
            {
                HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request due to double click");
            }
            catch (IOException ignore)
            {
            }
            finally
            {
                facesContext.responseComplete();
            }
        }
    }

    private boolean isHttpGetRequest(FacesContext facesContext)
    {
        return "GET".equalsIgnoreCase(((HttpServletRequest) facesContext.getExternalContext().getRequest()).getMethod());
    }
}
